package com.store.store.filter;

import com.store.store.util.BaseContext;
import com.store.store.util.R;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.mortbay.util.ajax.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 检查用户是否已经登录
 */
@WebFilter(filterName ="loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获得请求uri
        String uri = request.getRequestURI();

        //存储不需处理的路径
        String[] urls={
                "employee/login",
                "employee/logout",
                "static/**"
        };
        //不需要处理
        if(check(urls,uri) == true){
            filterChain.doFilter(request,response);
            return ;
        }

        //判断登录状态
        //已经登录
        if(request.getSession().getAttribute("employee")!=null){

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return ;
        }
        //未登录，返回未登录结果，通过输出流向客户端页面响应数据.
        response.getWriter().write(JSON.toString(R.error("NOTLOGIN")));

        /*log.info("拦截到请求：{}",request.getRequestURI());

        filterChain.doFilter(request,response);*/

    }

    /**
     * 对请求路径与不处理路径进行匹配判断
     * @param urls
     * @param requestUri
     * @return
     */
    public boolean check(String[] urls,String requestUri){
        for(String i:urls){
            boolean match = ANT_PATH_MATCHER.match(i, requestUri);
            if(match==true) return true;

        }
        return false;
    }
}
